<?php
namespace app\api\controller\v1;
use app\api\controller\RestBaseController;
use app\api\service\MemberService;
use app\api\validate\MemberValidate;
use app\common\library\redis\Redis;
use app\common\service\EmailTemplateService;
use think\exception\ValidateException;
use think\helper\Str;
use zyw\captcha\facade\Captcha;
use function app\api\controller\validate;

class Login extends RestBaseController
{
    public function register()
    {
         $post = $this->request->post();
         try {
             validate(MemberValidate::class)->scene("register")->check($post);
         } catch (ValidateException $e) {
              throw new ValidateException($e->getError());
         }
         $service = new MemberService();
         $res = $service->register($post["email"],$post["password"],$post["pid"]);
         $res ? $this->success("注册成功") :$this->error("注册失败");
    }

    public function login()
    {
        $post = $this->request->post();
        try {
            validate(MemberValidate::class)->scene("Login")->check($post);
        } catch (ValidateException $e) {
            throw new ValidateException($e->getError());
        }
        $service = new MemberService();
        $res = $service->login($post["email"],$post["password"]);
        if ($res>0) {
            $this->error(MemberService::MESSAGE[$res]);
        } else {
            $this->success(MemberService::MESSAGE[$res]);
        }
    }

    public function verify()
    {

         $this->success("ok",Captcha::create());
    }

    public function sendEmail()
    {
        $post = $this->request->post();
        try {
            validate(MemberValidate::class)->scene("send-email")->check($post);
        } catch (ValidateException $e) {
            throw new ValidateException($e->getError());
        }
    /*   if (!Captcha::check($post["code"],$post["verify_id"])) {
           $this->error("图形验证码错误");
       }*/
        $code = Str::random(4,1);
        $redis = Redis::getInstance();
        $redis->set("verify_id".$code,"1234");
        $service =new EmailTemplateService();
        $res = $service->sendEmail(1,$post["email"],["code"=>$code]);
        if ($res) {
            $this->success("发送成功");
        } else {
            $this->error("发送失败");
        }
    }
}